package com.zrl.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrl.project.model.entity.Likes;
import com.zrl.project.model.entity.User;
import com.zrl.project.service.LikesService;
import com.zrl.project.mapper.LikesMapper;
import com.zrl.project.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 13168
* @description 针对表【likes(用户喜欢以及博客点赞表)】的数据库操作Service实现
* @createDate 2023-03-28 19:30:37
*/
@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, Likes>
    implements LikesService{

    @Resource
    private UserService userService;

    @Override
    public Integer modifyLikeStatus(Likes likes) {
        Likes one = getExist(likes);
        if (one == null){
            save(likes);
            return 1;
        }
        removeById(one);
        return 0;
    }

    @Override
    public Boolean getLikeStatus(Likes likes) {
        Likes one = getExist(likes);
        if (one == null){
            return false;
        }
        return true;
    }

    @Override
    public List<User> getLikeUsers(Long id) {
        LambdaQueryWrapper<Likes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Likes::getBlogId,id);
        List<Likes> list = list(queryWrapper);
        if (list.isEmpty()){
            return new ArrayList<>();
        }
        List<Long> userIdList = list.stream()
                .map(Likes::getUserId)
                .collect(Collectors.toList());

        return userService.listByIds(userIdList);
    }

    /**
     * 查询是否存在指定Like对象
     * @param likes
     * @return
     */
    private Likes getExist(Likes likes) {
        LambdaQueryWrapper<Likes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Likes::getBlogId, likes.getBlogId());
        queryWrapper.eq(Likes::getUserId, likes.getUserId());
        return getOne(queryWrapper);
    }

}




